import { ipcMain, shell } from "electron";
import fs from "node:fs";
import child_process from "child_process";

ipcMain.on("shell:open-external", (event, ...args: Parameters<typeof shell.openExternal>) => {
  shell.openExternal(...args).catch((e: any) => {
    console.error("shell.openExternal error:", e);
  });
});

const notepad__ = "C:\\Program Files\\Notepad--\\Notepad--.exe";
const vscode = "C:\\Program Files\\Microsoft VS Code\\Code.exe";
const notepad = "C:\\Windows\\notepad.exe";
ipcMain.on("shell:open-file-via-editor", (event, filePath: string, preferVsc?: boolean) => {
  if (preferVsc && fs.existsSync(vscode)) {
    child_process.spawn(vscode, [filePath], { detached: true });
    return;
  }
  if (fs.existsSync(notepad__)) {
    child_process.spawn(notepad__, [filePath], { detached: true });
    return;
  }
  if (fs.existsSync(vscode)) {
    child_process.spawn(vscode, [filePath], { detached: true });
    return;
  }
  child_process.spawn(notepad, [filePath], { detached: true });
});
